<script>
export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      chartConfig: {
        chart: null,
        option: {
          grid: {
            left: '2%',
            right: '2%',
            bottom: '2%',
            containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (c) {
              return '时间：' + c[0].name + '<br>能耗：' + c[0].value + ' kgce';
            }
          },
          xAxis: {
            type: 'category',
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: 'kgce',
              type: 'line',
              data: []
            }
          ]
        }
      },
      dialogOption: {
        dialogVisible: false,
        selected: {
          subjectName: "",
          subjectType: "",
          increaseStandValue: "",
          increaseRealValue: "",
          increaseCashValue: "",
        }
      },
      collapsable: true,
      filterText: '',
      treeMap: {
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      labelClassName:"bg-color-orange",
      data: {},
      selectList: {
        selected: null,
        map: {},
        content: {},
        data: []
      },
      datePick: {
        from: new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7),
        end: new Date()
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  created() {
    this.$nextTick(() => {
      const orgTreeRef = this.$refs.orgTree;
      setTimeout(function () {
        const orgTree = orgTreeRef.$el;
        orgTree.addEventListener('wheel', function (event) {
          event.preventDefault(); // 阻止默认的滚动行为
          const scale = orgTree.style.transform
          let percents = scale.substring(scale.indexOf('(') + 1, scale.indexOf(')')) * 100;
          if (event.deltaY > 0) {
            percents = percents - 5
          }else {
            percents = percents + 5
          }
          orgTree.style.transform = 'scale(' + percents * 1.0/100 + ')'
        })
      }, 3000)
    })
  },
  methods: {
    initChart: function (content) {
      const list = content.list
      const sumValue = this.sumValue(list);
      this.dialogOption.selected.increaseRealValue = sumValue.increaseRealValue
      this.dialogOption.selected.increaseStandValue = sumValue.increaseStandValue
      this.dialogOption.selected.increaseCashValue = sumValue.increaseCashValue
      this.chartConfig.option.xAxis.data = [];
      this.chartConfig.option.series[0].data = [];
      for (let i = 0; i < list.length; i ++) {
        const item = list[i]
        this.chartConfig.option.xAxis.data.push(item.time);
        this.chartConfig.option.series[0].data.push(this.$doubleVal(item.increaseStandValue));
      }
      this.$nextTick(() => {
        this.chartConfig.chart = this.$echarts.init(this.$refs.subjectMapDayOnlineChart)
        this.chartConfig.chart.setOption(this.chartConfig.option)
      })
    },
    sumValue: function (list) {
      let standVal = 0;
      let realVal = 0;
      let cashVal = 0
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        standVal = standVal + item.increaseStandValue
        realVal = realVal + item.increaseRealValue
        cashVal = cashVal + item.increaseCashValue
      }
      if (this.selectList.selected == null) {
        realVal = '--'
      }else {
        realVal = this.$doubleLab(realVal)
      }
      return {
        increaseStandValue: this.$doubleLab(standVal),
        increaseRealValue: realVal,
        increaseCashValue: this.$doubleLab(cashVal),
      }
    },
    getEnergyUnite: function () {
      const selected = this.selectList.selected
      if (selected === null) {
        return ''
      }
      let unit = ''
      this.selectList.data.forEach(d => {
        if (d.id === selected) {
          unit = d.unite
        }
      })
      return unit
    },
    fetchEachSubjectEnergyInfo: function (subjectId, subjectType, after) {
      const fromDate = this.$getTimeInfo(this.datePick.from).toDay + ' 00:00:00';
      const toDate = this.$getTimeInfo(this.datePick.end).toDay + ' 23:59:59';
      let toDateType = 'hour'
      const dis = new Date(toDate).getTime() - new Date(fromDate).getTime()
      if (dis > 1000 * 60 * 60 * 27 * 5) {
        toDateType = 'day'
      }
      const data = {
        content: {
          fromDate: fromDate,
          toDateType: toDateType,
          toDate: toDate,
          subjectId: subjectId,
          subjectType: subjectType,
          energyId: this.selectList.selected
        }
      }
      this.$axios({url:'/ems/client/index/energy/time/trend', data: data}).then((content) => {
        after(content)
      })
    },
    fillItemContent: function (item, content) {
      const val = this.sumValue(content.list);
      const selected = this.selectList
      item.innerHTML = '综合能耗（标准煤）：'
          + val.increaseStandValue
          + ' '
          + selected.content.standUnite
          + '<br>综合能耗（货币）：'
          + val.increaseCashValue
          + ' '
          + selected.content.cashUnite
          + '<br>单位能耗：'
          + val.increaseRealValue
          + ' '
          + this.getEnergyUnite()
    },
    fetchSubjectEnergyInfo: function (itemArr, i) {
      const item = itemArr[i];
      if (item && item.classList && item.classList.length === 2) {
        const cls = item.classList;
        let info = cls[0].indexOf('subject_') === 0 ? cls[0].split('_'): cls[1].split('_');
        const subjectId = info[1];
        const subjectType = info[2];
        const fetchSubjectEnergyInfo = this.fetchSubjectEnergyInfo
        const fillItemContent = this.fillItemContent
        const afterFuc = function (content) {
          fillItemContent(item, content)
          fetchSubjectEnergyInfo(itemArr, ++i)
        }
        this.fetchEachSubjectEnergyInfo(subjectId, subjectType, afterFuc)
      }
    },
    fetchSubjectEnergyInfoPre: function() {
      const itemArr = this.$refs.orgTree.$el.querySelectorAll('.org-tree-subject-item');
      if (itemArr.length > 0) {
        this.fetchSubjectEnergyInfo(itemArr, 0)
      }
    },
    fetchData: function() {
      const data = {content: {excludeTypes:["DIAGRAM", "METER", "POINT", "GATEWAY"]}}
      this.$axios({url:'/ems/client/energy/search/subject/tree',data: data}).then((content) => {
        if (content.list && content.list.length > 0) {
          this.data = content.list
          this.toggleExpand(this.data[0],true);
        }
        this.$axios({url:'/ems/client/index/energy/list',data: {content: {}}}).then((content) => {
          this.selectList.data = content.list
          this.selectList.content = content
          this.selectList.data.unshift({id: null, name: '所有'})
        });
      });
      setTimeout(this.fetchSubjectEnergyInfoPre, 2500)
    },
    queryData: function () {
      this.fetchSubjectEnergyInfoPre()
    },
    showDialogDetail: function (e,data) {
      const subjectId = data.id
      const subjectType = data.type
      this.dialogOption.dialogVisible = true
      this.dialogOption.selected.subjectType = subjectType
      this.dialogOption.selected.subjectName = data.label
      this.fetchEachSubjectEnergyInfo(subjectId, subjectType, this.initChart)
    },
    collapse(list) {
      list.forEach((child)=> {
        if (child.expand) {
          child.expand = false;
        }
        child.children && this.collapse(child.children);
      });
    },
    onExpand: function (e, data) {
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, "expand", true);
      }
      if (data.children && data.children.length > 0) {
        for (let i = 0; i < data.children.length; i ++) {
          const item = data.children[i]
          this.fetchEachSubjectEnergyInfo(item.id, item.type, content => {
            const cls = '.subject_' + item.id + '_' + item.type
            this.$nextTick(() => {
              const item = this.$refs.orgTree.$el.querySelectorAll(cls);

              if (item.length > 0) {
                this.fillItemContent(item[0], content)
              }
            })
          })
        }
      }
    },
    toggleExpand(data, val) {
      if (Array.isArray(data)) {
        data.forEach((item)=> {
          this.$set(item, "expand", val);
          if (item.children) {
            //this.toggleExpand(item.children, val);
          }
        });
      } else {
        this.$set(data, "expand", val);
        if (data.children) {
          //this.toggleExpand(data.children, val);
        }
      }
    },
    filterNode: function(value, data) {
      if (!value) return true;
      const arr = value.split(' ');
      let match = true;
      for (let i = 0; i < arr.length; i ++) {
        const item = arr[i].trim()
        if (item === '') {
          continue
        }
        if (data.label.indexOf(item) === -1) {
          match = false
          break;
        }
      }
      return match;
    },
    renderContent: function (h, node) {
      return h('span', [
        node.label,
        h('br'),
        h('div', {style: 'text-align:left;', class: ['org-tree-subject-item', 'subject_' + node.id + '_' + node.type]}, [
          '加载中...'
        ])
      ])
    }
  }
}
</script>
<template>
  <el-row>
    <el-col :span="6">
      开始时间： <el-date-picker v-model="datePick.from" type="date" placeholder="开始时间"></el-date-picker><br><br>
      结束时间： <el-date-picker v-model="datePick.end" type="date" placeholder="结束时间"></el-date-picker><br><br>
      能源类型： <el-select v-model="selectList.selected" filterable placeholder="请选择">
        <el-option v-for="item in selectList.data" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select><br><br>
      <el-button type="primary" @click="queryData">查询</el-button><br><br>
      <el-input placeholder="输入关键字进行过滤" v-model="filterText" style="width: 85%;"></el-input>
      <el-tree class="filter-tree" :data="data" default-expand-all :filter-node-method="filterNode" ref="tree" style="width: 85%;">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span style="font-size: 15px;border-radius: 3px;padding: 7px 1px;"><i class="el-icon-c-scale-to-original"/>
                &nbsp;{{ node.label }}
              </span>
              <span style="color: rgb(102, 177, 255)">
                <i class="el-icon-right" @click="showDialogDetail(null, data)"/>
              </span>
            </span>
      </el-tree>
    </el-col>
    <el-col :span="18">
      <div style="width: 100%;height: 100%;overflow: auto;">
        <vue2-org-tree :style="'transform: scale(1);min-height:700px;'" :collapsable="collapsable" ref="orgTree" :data="data[0]" :label-class-name="labelClassName" @on-node-click="showDialogDetail" :renderContent="renderContent" :labelWidth="200" @on-expand="onExpand"/>
      </div>
    </el-col>
    <el-dialog :visible.sync="dialogOption.dialogVisible" width="70%">
      <div style="height: 60px;line-height: 20px;text-align: left;">
        主体名称：{{dialogOption.selected.subjectName}}<br>
        主体类型：{{dialogOption.selected.subjectType === 'BUILDING' ? '建筑': (dialogOption.selected.subjectType === 'DEPARTMENT' ? '科室': '院所')}}<br>
        综合能耗（标准煤）：{{dialogOption.selected.increaseStandValue}} {{selectList.content.standUnite}}<br>
        <!-- 综合能耗（货币）：{{dialogOption.selected.increaseCashValue}} {{selectList.content.cashUnite}}<br> -->
        单位能耗：{{dialogOption.selected.increaseRealValue}} {{getEnergyUnite()}}<br>
      </div>
      <div ref="subjectMapDayOnlineChart" style="height: 300px;margin-top: 50px;"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogOption.dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>
<style>
.bg-color-orange {
  color: #fff;
  background-color: orange;
}
</style>
